<!-- 通知管理 -->
<template>
    <div class="container">
        <!-- 内容顶部栏 -->
        <div class="content-top">
            <el-input class="search-input" v-model="searchVal" :placeholder="toggleSearch ? '请输入ID' : '请输入标题'"></el-input>
            <!-- <el-tooltip :content="toggleSearch ? '切换为名称' : '切换为ID'" placement="bottom">
                <el-switch v-model="toggleSearch"
                    style="--el-switch-on-color: #13ce66; --el-switch-off-color: rgb(19, 122, 206)" />
            </el-tooltip> -->
            <el-button v-if="toggleSearch" icon="Search" @click="searchById" round>搜索</el-button>
            <el-button v-else icon="Search" @click="searchByName" round>搜索</el-button>
            <el-button @click="loadNoticeList" round>清除搜索</el-button>
            <el-button @click="createNotice" type="primary" round>创建通知</el-button>
            <div
                style="font-family: 微软雅黑;line-height:25px;margin-left: 500px;height:30px;font-size: 24px;border: 2px solid rgb(64, 158, 255);border-radius:5px;padding: 0px 20px; color: white;background-color: rgb(64, 158, 255);">
                通知管理</div>
        </div>

        <!-- 内容表格开始，border:表格边框 -->
        <el-table :data="NoticeList" border max-height="calc(100vh - 190px)">
            <el-table-column label="序号" type="index" align="center" width="85" />
            <el-table-column label="标题" prop="title" align="center" />
            <el-table-column label="内容" prop="content" align="center" />
            <el-table-column label="发布者" prop="nickName" align="center" width="120">
                <!-- <template v-slot="scope">
                    {{ getPublisherLabel(scope.row.publisher) }}
                </template> -->
            </el-table-column>
            <el-table-column label="接收者" prop="receiverName" align="center" width="85" />
            <el-table-column label="发布日期" prop="publishTime" align="center" width="120" />
            <el-table-column label="更新日期" prop="updateTime" align="center" width="120" />
            <el-table-column label="操作" align="center" width="220">
                <template v-slot="scope">
                    <!-- <el-button @click="editDialog(scope.row)" type="text"><el-icon>
                            <Edit />
                        </el-icon>编辑</el-button> -->
                    <el-button @click="del(scope.row)" type="text" style="color: red"><el-icon>
                            <Delete />
                        </el-icon>删除</el-button>
                    <!-- <el-button @click="submitComment" type="text" style="color: red">删除</el-button> -->
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div style="padding-left: calc(100% - 650px); text-align: right;margin-top: 10px">
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                :current-page="pageSetting.page_num" :page-sizes="[5, 10, 15, 20]" :page-size="pageSetting.page_size"
                layout="total, sizes, prev, pager, next, jumper" :total="pageSetting.total">
            </el-pagination>
        </div>

        <!-- 弹窗 -->
        <div>
            <el-dialog v-model="dialogVisible" :title="editFormTitle" :visible="dialogVisible" width="40%"
                :before-close="handleBeforeClose">
                <el-form :model="editFormData" :rules="editFormRules" label-position="left" ref="editFormRef">
                    <!-- <el-form-item label="通知编号" prop="noticeId">
                        <p>{{ editFormData.noticeId }}</p>
                    </el-form-item> -->
                    <el-form-item label="标题" prop="title">
                        <el-input v-model="editFormData.title" placeholder="请输入标题"></el-input>
                    </el-form-item>
                    <el-form-item label="内容" prop="content">
                        <el-input v-model="editFormData.content" placeholder="请输入内容"></el-input>
                    </el-form-item>
                    <!-- <el-form-item label="发布者" prop="nickName">
                        <el-input v-model="editFormData.nickName" disabled
                            :placeholder="publisherOption.nickName"></el-input>
                    </el-form-item> -->
                    <el-form-item label="选择用户类型" prop="receiver">
                        <el-radio-group v-model="radio" :change=selectUser()>
                            <el-radio label="teacher">老师</el-radio>
                            <el-radio label="judge">评委</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="选择用户" prop="receiver">
                        <el-select v-model="receiver" multiple collapse-tags collapse-tags-tooltip
                            :max-collapse-tags="3" placeholder="选择用户">
                            <el-option v-for="item in userList" :key="item.userId" :label="item.nickName"
                                :value="item.userId" />
                        </el-select>
                    </el-form-item>
                </el-form>
                <solt name="footer" style="padding-left: 65%;">
                    <el-button @click="handleBeforeClose">取消</el-button>
                    <el-button type="primary" @click="handleConfirm">确认</el-button>
                </solt>
            </el-dialog>
        </div>
    </div>
</template>

<script setup>
import {
    GetNoticeList,
    GetNoticeById,
    AddNoticeList,
    UpdateNoticeList,
    DeleteNoticeList,
    GetNoticeByName
} from "@/api/back/notice";
import { GetUserList } from "@/api/back/user";
import { ref, onMounted } from 'vue';
import { ElMessage, messageConfig } from "element-plus";

const toggleSearch = ref(false);
// ----------分页查询----------
const pageSetting = ref({
    page_num: 1,
    page_size: 10,
    total: 0
});
// ----------分页查询----------

// ----------分页功能----------
function handleSizeChange(size) {
    console.log(size, 'size');
    pageSetting.value.page_size = size;
    console.log(pageSetting.value.page_size);
    NoticeList.value = [];
    loadNoticeList();
}
function handleCurrentChange(page) {
    console.log(page, 'page');
    pageSetting.value.page_num = page;
    console.log(pageSetting.value.page_num);
    NoticeList.value = [];
    loadNoticeList();
}
// ----------分页功能----------

// ----------获取赛事动态数据列表----------
// 存放数据列表
const NoticeList = ref([]);
// 获取列表
async function loadNoticeList() {
    try {
        const response = await GetNoticeList(pageSetting.value);
        if (response.data) {
            NoticeList.value = [];
            NoticeList.value.push(...response.data.pageList);
            pageSetting.value.page_num = response.data.pageNum;
            pageSetting.value.page_size = response.data.pageSize;
            pageSetting.value.total = response.data.total;
            console.log("获取数据列表成功", NoticeList.value);
        }
    } catch (error) {
        console.error("获取数据列表失败", error);
    }
}
// ----------获取赛事动态数据列表----------

// ----------搜索功能----------
// 存放搜索的值
const searchVal = ref("");
// 搜索功能
async function searchById() {
    try {
        if (searchVal.value == null || searchVal.value == "") {
            GetNoticeList(pageSetting.value);
        } else {
            const v = {
                search: searchVal.value, // 以键值对的形式提供参数
                page: pageSetting.value
            };
            NoticeList.value = [];
            const response = await GetNoticeById(v);
            NoticeList.value.push(...response.data);
            console.log("搜索成功", response);
        }
    } catch (error) {
        console.log("搜索错误", error);
    }
}
const searchByName = async () => {
    if (searchVal.value == null || searchVal.value == "") {
        ElMessage({
            message: "请输入搜索内容",
            type: "warning"
        });
        return;
    }
    NoticeList.value = [];
    const response = await GetNoticeByName({ search: searchVal.value });
    if (response.data.length == 0) {
        ElMessage({
            message: "未找到相关通知",
            type: "error",
        });
    } else {
        NoticeList.value.push(...response.data);
    }
    console.log("搜索成功", response);
}
// ----------搜索功能----------

// ----------删除功能----------
async function del(row) {
    const id = row.noticeId;
    try {
        await DeleteNoticeList(id);
        NoticeList.value = [];
        await loadNoticeList();
        console.log("删除成功");
        ElMessage({
            message: "删除成功",
            type: "success",
            ...messageConfig,
        });
    } catch (error) {
        console.error("删除失败", error);
    }
}
// ----------删除功能----------

// ----------弹窗选项----------
// 获取当前登录的用户数据，显示发布者
const publisherOption = JSON.parse(localStorage.getItem('userInfo')).userData[0];

// 获取用户列表
// 存放所有用户数据列表
const userList = ref([]);
const optionsTeacher = ref({});
const optionsJudge = ref({});
// 获取所有用户数据列表
async function getUserList() {
    // userList.value = [];
    try {
        console.log(pageSetting.value)
        const response = await GetUserList(pageSetting.value);
        if (response.data) {
            for (let i = 0; i < response.data.pageList.length; i++) {
                // 去除超级管理员
                if (response.data.pageList[i].roleId != 0 && response.data.pageList[i].roleId == 1) {
                    optionsTeacher.value[i] = response.data.pageList[i]
                }
                if (response.data.pageList[i].roleId != 0 && response.data.pageList[i].roleId == 2) {
                    optionsJudge.value[i] = response.data.pageList[i]
                }
            }
            // pageSetting.value.page_num = 1;
            // pageSetting.value.page_size = 99;
            pageSetting.value.total = response.data.total;
            console.log("获取老师列表成功", optionsTeacher.value);
            console.log("获取评委列表成功", optionsJudge.value);
            console.log("获取用户列表成功", userList.value);
        }
    } catch (error) {
        console.error("获取用户列表失败", error);
    }
}

const radio = ref("");
async function selectUser() {
    try {
        if (radio.value == "teacher") {
            userList.value = optionsTeacher.value
            // console.log("老师", optionsTeacher.value)
        } else if (radio.value == "judge") {
            userList.value = optionsJudge.value
            // console.log("评委", optionsJudge.value)
        }
    } catch (error) {
        console.error("失败", error);
    }
}




// ----------弹窗选项----------


// ----------弹窗功能----------
// 控制弹窗是否显示
const dialogVisible = ref(false);
const edit = ref(false);
const add = ref(false);
// 弹窗标题
const editFormTitle = ref("");

// 编辑数据变量
const editFormData = ref({
    noticeId: "",
    title: "",
    content: "",
    publisher: publisherOption.userId,
    nickName: publisherOption.nickName,
    receiver: "",
});

const receiver = ref();

// 控制添加弹窗
const createNotice = () => {
    editFormTitle.value = "创建通知"
    dialogVisible.value = true;
    add.value = true;
};

// 编辑弹窗数据
// const editDialog = (rowData) => {
//     editFormTitle.value = "编辑通知",
//         editFormData.value = {
//             noticeId: rowData.noticeId,
//             title: rowData.title,
//             content: rowData.content,
//             publisher: editFormData.value.publisher,
//             receiver: rowData.receiver,
//         }
//     dialogVisible.value = true;
//     edit.value = true
// }

// 处理添加或编辑弹窗的”确认“按钮
async function handleConfirm() {
    try {
        if (edit.value) {
            console.log("编辑成功", editFormData.value);
            await UpdateNoticeList(editFormData.value);
            edit.value = false;
        } else if (add.value) {
            for (let i = 0; i < receiver.value.length; i++) {
                console.log("receiver",receiver.value[i])
                editFormData.value.receiver = receiver.value[i];
                await AddNoticeList(editFormData.value);
            }
            console.log("添加成功");
            radio.value = "",
            receiver.value = "",
            add.value = false;
        }
    } catch (error) {
        console.error("失败", error);
    }
    dialogVisible.value = false;
    NoticeList.value = [];
    await loadNoticeList();
}

// 处理弹窗取消按钮
function handleBeforeClose() {
    radio.value = "",
    receiver.value = "",
    editFormData.value = {
        noticeId: "",
        title: "",
        content: "",
        publisher: editFormData.value.publisher,
        receiver: "",
    }
    dialogVisible.value = false;
    edit.value = false;
    add.value = false;
    console.log("取消")
}
// ----------弹窗功能----------

onMounted(() => {
    loadNoticeList();
    getUserList();
});
</script>
